package main

import (
	"github.com/gin-gonic/gin"
	"html/template"
	"my_go_open/utils/ws"
)

var html = template.Must(template.New("index").Parse(`
<script type="text/javascript">
    (function () {
		conn = new WebSocket("ws://127.0.0.1:8088/ws");
		conn.onopen = (ev) => {
			console.log("opening");
			conn.send('hi');
		};
		conn.onerror = (ev) => {
			console.log("on error");
			conn = null;
		};
		conn.onmessage = (ev) => {
			console.log("on msg");
			console.log(ev.data);
		};
		conn.onclose = (ev) => {
			console.log("on close")
			conn = null;
		};
        setInterval(function () {
            if (conn != null) {
                conn.send('{"content":' + (new Date()).getTime() + '}');
            }
        }, 3000);
    })();
</script>
`))

func main() {
	hub := ws.NewHub(nil, nil, nil)
	r := gin.Default()
	r.SetHTMLTemplate(html)
	r.GET("/", func(c *gin.Context) {
		c.HTML(200, "index", nil)
	})
	r.GET("/ws", func(c *gin.Context) {
		conn, err := ws.NewConn(c.Writer, c.Request)
		if err != nil {
			c.AbortWithError(403, err)
			return
		}
		groups := make([]string, 0)
		ws.NewClient(hub, conn, "", groups, nil, nil)
	})
	r.Run("127.0.0.1:8088")
}
